package com.pxxy.yuyi.utils;

import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by IntelliJ IDEA
 *
 * @Author : XuWen
 * @create 2021/6/16 23:28
 */
public class ImgeUtils {
    public static String imgeLoad(MultipartFile fileImg, HttpServletRequest request,String load) throws IOException {
        //获取文件原始名称
        String filename = fileImg.getOriginalFilename();
        //获取后缀，用于判断图片格式
        String suffix = FilenameUtils.getExtension(filename);
        //获取当前时间
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        //用当前时间命名文件，使文件名不重复
        String prefix = format.format(new Date());
        //也可以用这个方法命名图片，让图片名唯一
        //String prefix = UUID.randomUUID().toString().replaceAll("_","");

        //把图片放在项目根目录中，方便取出
//        String url = request.getSession().getServletContext().getRealPath("");
//        System.out.println(url);
        String realPath = request.getSession().getServletContext().getRealPath("/"+load);
        //新文件名
        String newFileName =prefix+"."+suffix;
       // System.out.println("newFileName==="+newFileName);
        //把图片写入磁盘
        fileImg.transferTo(new File(realPath+"/"+newFileName));
       String imgLoad= load+"/"+newFileName;
        return imgLoad;
    }
}
